import { ref, reactive } from "vue";
import type {
  HomePageData,
  UserStatistics,
  TaskStatistics,
  ToolStatistics,
  SystemStatistics,
  ChartData,
  ActivityRecord,
  NotificationItem,
  QuickAccessItem
} from "../types/home";
import { BusinessOptType, BusinessType } from "@/enums/sysEnum";
import apiService from "@/api/services/apiService";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/modules/user";
import { storeToRefs } from "pinia";
import { ItemState } from "@/enums/businessEnum";

const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);

/**
 * 首页数据管理 Hook
 */
export const useHomeData = () => {
  const loading = ref(false);
  const lastUpdateTime = ref<Date>(new Date());

  // 响应式数据
  const homeData = reactive<HomePageData>({
    userStats: {
      totalUsers: 0,
      onlineUsers: 0,
      todayNewUsers: 0,
      userStatusDistribution: { active: 0, inactive: 0, pending: 0 }
    },
    taskStats: {
      pendingTasks: 0,
      completedTasks: 0,
      weeklyProgress: 0,
      priorityDistribution: { high: 0, medium: 0, low: 0 }
    },
    toolStats: {
      totalUsage: 0,
      mostPopularTool: "",
      todayUsage: 0,
      userActivity: 0,
      toolUsageDetails: {}
    },
    systemStats: {
      uptime: new Date(),
      apiResponseTime: 0,
      errorCount: 0,
      resourceUsage: { cpu: 0, memory: 0, disk: 0 }
    },
    chartData: {
      userGrowthTrend: { dates: [], values: [] },
      moduleUsageDistribution: [],
      taskCompletionChart: { categories: [], series: [] },
      systemActivityHeatmap: { hours: [], days: [], data: [] }
    },
    recentActivities: [],
    notifications: [],
    quickAccessItems: []
  });

  // 获取用户统计数据
  const fetchUserStatistics = async (): Promise<UserStatistics> => {
    try {
      // 获取用户总数
      const userCount = await apiService.findCount<number>("users", {});

      // 获取当天登录用户数
      let curDate = new Date();
      let [year, month, day] = [curDate.getFullYear(), curDate.getMonth(), curDate.getDate()];
      let startDate = new Date(year, month, day);
      let endDate = new Date(year, month, day, 23, 59, 59);
      let groupCondition = [
        { $project: { optType: 1, optUser: 1, optDate: 1, _id: 1 } },
        { $match: { optDate: { $gte: startDate, $lte: endDate }, optType: "LOGIN" } },
        { $group: { _id: { optUser: "$optUser" }, count: { $sum: 1 } } }
      ];
      const loginData = await apiService.group<any[]>("userAction", groupCondition);
      let loginCount = 0;
      if (loginData) {
        loginData.data.forEach(item => {
          loginCount += item.value;
        });
      }

      return {
        totalUsers: userCount.data || 200,
        onlineUsers: loginData.data.length || 187,
        todayNewUsers: loginCount || 23,
        userStatusDistribution: {
          active: Math.floor(userCount.data * 0.8) || 998,
          inactive: Math.floor(userCount.data * 0.15) || 187,
          pending: Math.floor(userCount.data * 0.05) || 63
        }
      };
    } catch (error) {
      console.error("获取用户统计失败:", error);
      return {
        totalUsers: 1248,
        onlineUsers: 187,
        todayNewUsers: 23,
        userStatusDistribution: { active: 998, inactive: 187, pending: 63 }
      };
    }
  };

  // 获取任务统计数据
  const fetchTaskStatistics = async (): Promise<TaskStatistics> => {
    try {
      let curDate = new Date();
      let [year] = [curDate.getFullYear()];
      let startDate = new Date(year, 0, 0, 0, 0, 0);
      let groupCondition = [
        { $project: { year: 1, level: 1, state: 1, _id: 1 } },
        { $match: { year: { $gte: startDate, $lte: curDate } } },
        { $group: { _id: { state: "$state", level: "$level" }, count: { $sum: 1 } } }
      ];

      const { data } = await apiService.group<any[]>("item", groupCondition);

      let pendingTasks = 0;
      let completedTasks = 0;

      data?.forEach((item: any) => {
        pendingTasks += item.count;
        if (item._id === ItemState.DONE) {
          completedTasks += item.count;
        }
      });

      return {
        pendingTasks: pendingTasks || 0,
        completedTasks: completedTasks || 0,
        weeklyProgress: Math.round((completedTasks / (pendingTasks - completedTasks)) * 100) || 0,
        priorityDistribution: {
          high: Math.floor(pendingTasks * 0.3) || 14,
          medium: Math.floor(pendingTasks * 0.5) || 23,
          low: Math.floor(pendingTasks * 0.2) || 8
        }
      };
    } catch (error) {
      console.error("获取任务统计失败:", error);
      return {
        pendingTasks: 45,
        completedTasks: 128,
        weeklyProgress: 74,
        priorityDistribution: { high: 14, medium: 23, low: 8 }
      };
    }
  };

  // 获取工具使用统计
  const fetchToolStatistics = async (): Promise<ToolStatistics> => {
    try {
      const toolTypes = [
        BusinessType.Tool_base64,
        BusinessType.Tool_datetime,
        BusinessType.Tool_byte,
        BusinessType.Tool_imageCompress,
        BusinessType.Tool_dataGenerator,
        BusinessType.Tool_jsonFormatter
      ];

      // 获取总使用次数
      const totalCountCondition = [
        {
          $match: {
            businessType: { $in: toolTypes }
          }
        },
        {
          $group: {
            _id: "$businessType",
            count: { $sum: 1 }
          }
        }
      ];

      // 获取当天使用次数
      const todayStart = new Date(new Date().setHours(0, 0, 0, 0));
      const todayCountCondition = [
        {
          $match: {
            businessType: { $in: toolTypes },
            optDate: {
              $ne: null,
              $gte: todayStart
            }
          }
        },
        {
          $group: {
            _id: "$businessType",
            todayCount: { $sum: 1 }
          }
        }
      ];

      // 并行执行两个查询
      const [totalCountResult, todayCountResult] = await Promise.all([
        apiService.group("userAction", totalCountCondition),
        apiService.group("userAction", todayCountCondition)
      ]);

      let totalUsage = 0;
      let todayUsage = 0;
      let maxUsage = 0;
      let mostPopularTool = "";
      const toolUsageDetails: { [key: string]: number } = {};

      // 处理总使用次数
      if (Array.isArray(totalCountResult.data)) {
        totalCountResult.data.forEach((item: any) => {
          totalUsage += item.count;
          toolUsageDetails[item._id] = item.count;

          if (item.count > maxUsage) {
            maxUsage = item.count;
            mostPopularTool = item._id;
          }
        });
      }

      // 处理当天使用次数
      if (Array.isArray(todayCountResult.data)) {
        todayCountResult.data.forEach((item: any) => {
          todayUsage += item.todayCount;
        });
      }

      return {
        totalUsage: totalUsage || 892,
        mostPopularTool: mostPopularTool || "Tool_datetime",
        todayUsage: todayUsage || 0, // 如果没有当天数据，应该显示0
        userActivity: totalUsage > 0 ? Math.round((todayUsage / totalUsage) * 100) || 0 : 68,
        toolUsageDetails
      };
    } catch (error) {
      console.error("获取工具统计失败:", error);
      return {
        totalUsage: 892,
        mostPopularTool: "Tool_datetime",
        todayUsage: 0, // 出错时当天使用次数为0
        userActivity: 68,
        toolUsageDetails: {}
      };
    }
  };

  // 获取系统状态
  const fetchSystemStatistics = async (): Promise<SystemStatistics> => {
    const startTime = Date.now();

    try {
      // 通过简单的测试响应时间
      const testStart = Date.now();
      // 使用一个更简单的API调用来测试响应时间
      try {
        await apiService.findCount("counters", {});
      } catch {
        // 如果API调用失败，继续执行
      }
      const responseTime = Date.now() - testStart;

      // 计算系统运行时间（模拟）
      let uptimeData = await apiService.findPage<any>("userAction", {}, { pageNum: 1, pageSize: 1, sort: { optDate: 1 } });
      return {
        uptime: uptimeData.data.content[0].optDate,
        apiResponseTime: responseTime,
        errorCount: Math.floor(Math.random() * 5),
        resourceUsage: {
          cpu: Math.floor(Math.random() * 40) + 20,
          memory: Math.floor(Math.random() * 30) + 40,
          disk: Math.floor(Math.random() * 20) + 55
        }
      };
    } catch (error) {
      const responseTime = Date.now() - startTime;
      return {
        uptime: new Date(),
        apiResponseTime: responseTime,
        errorCount: 2,
        resourceUsage: { cpu: 35, memory: 62, disk: 68 }
      };
    }
  };

  // 获取最近活动
  const fetchRecentActivities = async (): Promise<ActivityRecord[]> => {
    try {
      const { data } = await apiService.findPage<any>(
        "userAction",
        { optUser: userInfo.value._id },
        {
          pageNum: 1,
          pageSize: 20,
          sort: { optDate: -1 }
        }
      );

      return (
        data.content?.map((item: any) => ({
          id: item._id,
          userName: item.userName || "",
          action: item.optInfo || "操作",
          module: item.businessType || "系统",
          description: item.description || `${item.optInfo}`,
          timestamp: item.optDate,
          type: getActivityType(item.businessType)
        })) || []
      );
    } catch (error) {
      console.error("获取活动记录失败:", error);
      return [];
    }
  };

  // 获取系统通知
  const fetchNotifications = async (): Promise<NotificationItem[]> => {
    try {
      let groupCondition = [
        {
          $lookup: {
            from: "messagestates",
            localField: "messageId",
            foreignField: "messageId",
            as: "ms"
          }
        },
        {
          $match: {
            "ms.user": { $ne: userInfo.value._id },
            $or: [{ range: "all" }, { toUsers: { $in: [userInfo.value._id] } }]
          }
        },
        { $sort: { create_at: -1 } }
      ];
      let { data } = await apiService.groupNoLoading<any>("message", groupCondition);
      return (
        data?.map((item: any) => ({
          id: item._id,
          title: item.title || "系统通知",
          content: item.title || "您有新的系统消息",
          type: item.type || "announcement",
          priority: item.priority || "medium",
          isRead: item.isRead || false,
          createTime: item.create_at
        })) || []
      );
    } catch (error) {
      console.error("获取通知失败:", error);
      return [];
    }
  };

  // 获取快速访问菜单
  const getQuickAccessItems = (): QuickAccessItem[] => {
    return [
      {
        id: "tools",
        title: "常用工具",
        icon: "Tools",
        route: "/tools",
        color: "var(--el-color-primary)",
        isAiGenerated: true
      },
      {
        id: "worklog",
        title: "工作日志",
        icon: "List",
        route: "/worklog",
        color: "var(--el-color-primary)",
        isAiGenerated: true
      },
      {
        id: "safeNote",
        title: "安全记事本",
        icon: "Management",
        route: "/tools/safeNote",
        color: "var(--el-color-primary)",
        isAiGenerated: true
      },
      {
        id: "rushJob",
        title: "突击申请",
        icon: "Bicycle",
        route: "/rd/rushjob",
        color: "var(--el-color-primary)",
        isAiGenerated: true
      },
      {
        id: "user-manage",
        title: "用户管理",
        icon: "User",
        route: "/system/userManage",
        color: "var(--el-color-primary)"
      },
      {
        id: "role-manage",
        title: "权限管理",
        icon: "Lock",
        route: "/auth/roleAuth",
        color: "var(--el-color-primary)"
      },
      {
        id: "system-config",
        title: "参数设置",
        icon: "Setting",
        route: "/system/paramManage",
        color: "var(--el-color-primary)"
      }
    ];
  };

  // 获取活动类型
  const getActivityType = (businessType: string): ActivityRecord["type"] => {
    if (businessType === BusinessType.LOGIN) return "login";
    if (businessType === BusinessType.TASK) return "task";
    if (businessType === BusinessType.SYS) return "system";
    return "operation";
  };

  // 获取图表数据
  const fetchChartData = async (): Promise<ChartData> => {
    //统计用户近一个月每天登录次数作为图标数据
    let groupCondition = [
      {
        $match: {
          optType: BusinessOptType.LOGIN,
          optDate: {
            $gte: new Date(new Date().getTime() - 30 * 24 * 60 * 60 * 1000)
          }
        }
      },
      {
        $group: {
          _id: {
            $dateToString: {
              format: "%Y-%m-%d",
              date: "$optDate"
            }
          },
          count: { $sum: 1 }
        }
      },
      {
        $sort: { _id: 1 }
      }
    ];
    let { data } = await apiService.groupNoLoading<any>("userAction", groupCondition);

    // 处理真实数据
    const dates: string[] = [];
    const values: number[] = [];

    if (Array.isArray(data) && data.length > 0) {
      data.forEach((item: any) => {
        dates.push(item._id);
        values.push(item.count);
      });
    }

    // 如果没有数据，使用模拟数据
    if (dates.length === 0) {
      for (let i = 0; i < 7; i++) {
        const date = new Date();
        date.setDate(date.getDate() - 6 + i);
        dates.push(date.toLocaleDateString());
        values.push(Math.floor(Math.random() * 50) + 100);
      }
    }
    return {
      userGrowthTrend: { dates, values },
      moduleUsageDistribution: [
        { name: "用户管理", value: 35 },
        { name: "任务管理", value: 25 },
        { name: "工具使用", value: 20 },
        { name: "系统配置", value: 12 },
        { name: "其他", value: 8 }
      ],
      taskCompletionChart: {
        categories: ["周一", "周二", "周三", "周四", "周五"],
        series: [
          {
            name: "已完成",
            data: [23, 28, 31, 26, 35]
          },
          {
            name: "进行中",
            data: [12, 15, 18, 14, 20]
          }
        ]
      },
      systemActivityHeatmap: {
        hours: Array.from({ length: 24 }, (_, i) => `${i}:00`),
        days: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
        data: Array.from({ length: 7 }, () => Array.from({ length: 24 }, () => Math.floor(Math.random() * 100)))
      }
    };
  };

  // 刷新所有数据
  const refreshData = async () => {
    loading.value = true;
    try {
      const [userStats, taskStats, toolStats, systemStats, chartData, activities, notifications] = await Promise.all([
        fetchUserStatistics(),
        fetchTaskStatistics(),
        fetchToolStatistics(),
        fetchSystemStatistics(),
        fetchChartData(),
        fetchRecentActivities(),
        fetchNotifications()
      ]);

      Object.assign(homeData, {
        userStats,
        taskStats,
        toolStats,
        systemStats,
        chartData,
        recentActivities: activities,
        notifications,
        quickAccessItems: getQuickAccessItems()
      });

      lastUpdateTime.value = new Date();
      ElMessage.success("数据刷新成功");
    } catch (error) {
      console.error("数据刷新失败:", error);
      ElMessage.error("数据刷新失败");
    } finally {
      loading.value = false;
    }
  };

  // 初始化数据
  const initData = async () => {
    await refreshData();
  };

  return {
    homeData,
    loading,
    lastUpdateTime,
    refreshData,
    initData
  };
};
